package world.xuewei.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import world.xuewei.model.entity.Orders;
import world.xuewei.model.entity.R;
import world.xuewei.model.vo.PayVo;
import world.xuewei.component.AlipayTemplate;
import org.springframework.stereotype.Controller;
import world.xuewei.service.OrdersService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping("/alipay")
@Slf4j
public class AlipayController {
    @Resource
    private AlipayTemplate alipayTemplate;

    @Resource
    private OrdersService ordersService;

    /**
     * 支付接口
     */
    @GetMapping(value = "/pay/{orderNumber}")
    @ResponseBody
    public String pay(@PathVariable String orderNumber) throws Exception {
        // 1. 获取订单信息
        Orders order = ordersService.getOrderDetail(orderNumber);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (order.getOrderStatus() != 0) {
            throw new RuntimeException("订单状态不正确");
        }

        // 2. 构建支付参数
        PayVo payVo = new PayVo();
        payVo.setOutTradeNo(order.getOrderNumber());
        payVo.setTotalAmount(order.getPayAmount().toString());
        payVo.setSubject("咖啡订单-" + order.getOrderNumber());
        payVo.setBody("咖啡订单");


        // 3. 获取支付表单
        String form = alipayTemplate.pay(payVo);
        return form;
    }

    /**
     * 支付异步通知
     */
    @PostMapping("/notify")
    public String handleAlipayNotify(HttpServletRequest request) throws AlipayApiException {
        log.info("收到支付宝异步通知");
        // 1. 获取支付宝POST过来的信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        // 2. 验签
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayTemplate.getAlipayPublicKey(),
                alipayTemplate.getCharset(),
                alipayTemplate.getSignType());

        if (signVerified) {
            String orderNumber = params.get("out_trade_no");
            String tradeStatus = params.get("trade_status");

            // 3. 判断交易状态
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                try {
                    // 4. 处理支付成功逻辑
                    ordersService.payOrder(orderNumber);
                    return "success";
                } catch (Exception e) {
                    log.error("支付异步通知处理失败", e);
                }
            }
        }else {
            log.error("验签失败");
        }
        return "fail";
    }

    /**
     * 支付同步回调
     */
    @GetMapping("/return")
    public R handleAlipayReturn(@RequestParam Map<String, String> params) throws AlipayApiException {
        log.info("收到支付宝同步回调");
        // 1. 验签
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayTemplate.getAlipayPublicKey(),
                alipayTemplate.getCharset(),
                alipayTemplate.getSignType());

        if (signVerified) {
            // 2. 获取订单号
            String orderNumber = params.get("out_trade_no");
            // 3. 跳转到订单详情页

            return R.ok().message("支付成功").data("orderNumber",orderNumber);
        }
        return R.ok().message("支付支付失败");
    }

}
